package org.qing.reactive.config.redis;

import java.util.ArrayList;
import java.util.List;

import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.core.ReactiveRedisTemplate;

@Configuration
@EnableCaching
public class RedisCacheConfig {

	@Bean
	@Primary
	public KeyGenerator keyGenerator() {
		// 当没有指定缓存的 key时来根据类名、方法名和方法参数来生成key
		return (target, method, params) -> {
			StringBuilder sb = new StringBuilder();
			sb.append(target.getClass().getName()).append(':').append(method.getName());
			if (params.length > 0) {
				sb.append('[');
				for (Object obj : params) {
					if (obj != null) {
						sb.append(obj.toString());
					}
				}
				sb.append(']');
			}
			return sb.toString();
		};
	}
	
	@Bean
	@Primary
	public CacheManager cacheManager(ReactiveRedisTemplate<String, Object> nativeCache) {
		ReactiveRedisCacheManager cacheManager = new ReactiveRedisCacheManager();
		List<Cache> caches = new ArrayList<Cache>();
		caches.add(new ReactiveRedisCache("cacheKey", nativeCache));
		cacheManager.setCaches(caches);
		return cacheManager;
	}
}
